# -*- coding: utf-8 -*-
import codecs

# 读取文件
with codecs.open('Terrain.cpp', 'r', encoding='utf-8-sig') as f:
    lines = f.readlines()

# 在 LoadTextures 函数开始处修改
new_lines = []
i = 0
while i < len(lines):
    line = lines[i]

    # 找到 LoadTextures 函数的开始
    if 'bool Terrain::LoadTextures(LPDIRECT3DDEVICE9 device)' in line:
        new_lines.append(line)  # bool Terrain::LoadTextures...
        new_lines.append(lines[i+1])  # {

        # 插入新的纹理加载代码
        new_lines.append('    // 从 111.png 加载草地纹理（强制不透明格式）\n')
        new_lines.append('    HRESULT hr = D3DXCreateTextureFromFileEx(\n')
        new_lines.append('        device,\n')
        new_lines.append('        L"111.png",\n')
        new_lines.append('        D3DX_DEFAULT, D3DX_DEFAULT, 1, 0,\n')
        new_lines.append('        D3DFMT_X8R8G8B8,  // 强制无Alpha通道\n')
        new_lines.append('        D3DPOOL_MANAGED,\n')
        new_lines.append('        D3DX_FILTER_LINEAR, D3DX_FILTER_LINEAR,\n')
        new_lines.append('        0, NULL, NULL,\n')
        new_lines.append('        &m_pTextureGrass\n')
        new_lines.append('    );\n')
        new_lines.append('    if (FAILED(hr))\n')
        new_lines.append('        return false;\n')
        new_lines.append('\n')

        # 跳过原来的程序生成纹理代码（从 HRESULT hr 到第一个 }\n 后）
        i += 2  # 跳过 { 之后的行
        bracket_count = 0
        skip_started = False

        while i < len(lines):
            if 'HRESULT hr = D3DXCreateTexture' in lines[i] and not skip_started:
                skip_started = True
                bracket_count = 0

            if skip_started:
                if '{' in lines[i]:
                    bracket_count += lines[i].count('{')
                if '}' in lines[i]:
                    bracket_count -= lines[i].count('}')

                # 找到匹配的结束大括号
                if bracket_count == -1:  # 这是 if (SUCCEEDED(hr)) { ... } 的结束
                    i += 1
                    break
            i += 1

        continue

    new_lines.append(line)
    i += 1

# 写回文件
with codecs.open('Terrain.cpp', 'w', encoding='utf-8-sig') as f:
    f.writelines(new_lines)

print("修复完成！")
